<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use Throwable;
use app\common\facade\Token;
use app\common\Frontend;
use app\common\library\Upload;
use app\common\model\BroadcastRoom;
use app\common\model\PublicStatus;
use app\common\model\RechargeCoin;
use app\common\model\ShopCart;
use app\common\model\User;
use app\common\model\Video;
use app\common\model\VipType;
use app\user\model\UserModel;
use DateTime;
use DateTimeZone;
use general\Random;
use think\facade\Db;
use think\Request;

class Index extends Frontend
{
    protected array $noNeedLogin = ['login', 'logout', 'userRegister', 'qqLogin', 'qqCodelogin','videoList'];

    public function initialize(): void
    {
        parent::initialize();
    }

    //用户登录-手机端登录支持 用户名 邮箱 手机号登录
    public function login()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post();

            if (!$params) {
                $this->error("参数不能为空");
            }
            // $type = $params['passwordShow'] == true ? 1 : 0;
            // $res = $this->auth->login($params['username'], $params['password'], true, $params['code'], 1);
            $res = $this->auth->login($params['username'], $params['password'], true, $params['auth_code'],1);
            if (isset($res) && $res === true) {
                $this->success(('Login succeeded!'), [
                    'site'             => [
                        'siteName'     => get_sys_config('site_name'),
                        'recordNumber' => get_sys_config('record_number'),
                        'version'      => get_sys_config('version'),
                        'cdnUrl'       => full_url(),
                        'upload'       => get_upload_config(),
                    ],
                    'payType' => PublicStatus::payType(),
                    'vipClass' => VipType::vipData(),
                    'coinType' => RechargeCoin::coinData(),
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => '/dashboard'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: ('登录失败，请重试或联系管理员~');
                $this->error($msg);
            }
        }
        $this->success('');
    }

    //用户退出
    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success('退出成功');
        }
    }

    //登录页视频
    public function videoList(){
        $model = Video::where(['status'=>PublicStatus::PAY_STATUS_ONE])->order('weigh desc')->select();
        $this->success('', [
            'list'   => $model,
            'remark' => '',
        ]);
    }


    public function qqLogin(): void
    {
        $qqOAuth = new \Yurun\OAuthLogin\QQ\OAuth2('102436623', '30jDTWLwKUQ8ctxp', 'http://www.kmanstage.com/home');
        $url = $qqOAuth->getAuthUrl();
        $_SESSION['YURUN_QQ_STATE'] = $qqOAuth->state;
        $this->success(('Login succeeded!'), [
            'state' => $qqOAuth->state,
            'routePath' => $url
        ]);
    }


    public function qqCodelogin()
    {
        if ($this->request->isGet()) {
            $code = $this->request->param('code');
            $state = $this->request->param('state');
            $qqOAuth = new \Yurun\OAuthLogin\QQ\OAuth2('102436623', '30jDTWLwKUQ8ctxp', 'http://www.kmanstage.com/home');
            $accessToken = $qqOAuth->getAccessToken($state);
            $userInfo = $qqOAuth->getUserInfo();
            $openid = $qqOAuth->openid;
            if ($userInfo['ret'] == 0) {
                $time = time();
                $ip   = request()->ip();
                $salt = Random::build('alnum', 16);
                $data = [
                    'group_id' => PublicStatus::PUBLIC_STATUS_ONE,
                    'label_id' => Random::build('numeric', 9),
                    'nickname' => $userInfo['nickname'],
                    'gender' => $userInfo['gender'] == '男' ? 0 : 1,
                    'open_id' => $openid,
                    'username' => preg_match("/^1[3-9]\d{9}$/", $userInfo['nickname']) ? substr_replace($userInfo['nickname'], '****', 3, 4) : $userInfo['nickname'],
                    'join_ip'        => $ip,
                    'join_time'      => $time,
                    'last_login_ip'   => $ip,
                    'last_login_time' => $time,
                    'salt'          => $salt,
                    'avatar' => $userInfo['figureurl_qq']
                ];
                $open = User::checkOpenId($data['open_id']);
                if ($open) {
                    $res =  $this->auth->direct($open['id']);
                } else {
                    $res = $this->auth->qqRegister($data, $accessToken);
                }
                if (isset($res) && $res === true) {
                    $this->success(('succeeded!'), [
                        'site'             => [
                            'siteName'     => get_sys_config('site_name'),
                            'recordNumber' => get_sys_config('record_number'),
                            'version'      => get_sys_config('version'),
                            'cdnUrl'       => full_url(),
                            'upload'       => get_upload_config(),
                        ],
                        'payType' => PublicStatus::payType(),
                        'vipClass' => VipType::vipData(),
                        'coinType' => RechargeCoin::coinData(),
                        'userInfo'  => $this->auth->getUserInfo(),
                        'routePath' => '/'
                    ]);
                } else {
                    $msg = $this->auth->getError();
                    $msg = $msg ?: ('登录失败，请重试或联系管理员~');
                    $this->error($msg);
                }
            } else {
                $this->error("登录失败");
            }
        }
        $this->success('');
    }


    //用户个人信息
    public function profile()
    {
        $model = $this->auth->getUserInfo();

        $this->success('', [
            'list'   => $model,
            'remark' => '',
        ]);
    }

    //注册
    public function userRegister(): void
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (!$params) {
                $this->error("参数不能为空");
            }
            //自定义名称
            $params['username'] = strtoupper(Random::build('alpha'));
            $params['email'] = $params['mobile'] . '@qq.com';
            $extend = [];
            if (!array_key_exists('avatar', $params)) {
                $extend['avatar'] = 'https://ykxyh.shunongyun.com/img/home/login.png';
            } else {
                $extend['avatar'] = $params['avatar'];
            }
            if (array_key_exists('wx_code', $params)) {
                $result = User::getWeChatPhone($params['wx_code']);
                $open = User::checkOpenId($result);
                if ($open) {
                    $this->error("open_id 已经存在");
                }
                $extend['open_id'] = $result;
            }
            $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email'], PublicStatus::PUBLIC_STATUS_ONE, $extend);
            if (isset($res) && $res === true) {
                $this->success(('Register succeeded!'), [
                    'site'             => [
                        'siteName'     => get_sys_config('site_name'),
                        'recordNumber' => get_sys_config('record_number'),
                        'version'      => get_sys_config('version'),
                        'cdnUrl'       => full_url(),
                        'upload'       => get_upload_config(),
                    ],
                    'userInfo'  => $this->auth->getUserInfo(),
                    'routePath' => 'url'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: ('登录失败，请重试或联系管理员~');
                $this->error($msg);
            }
        }
        $this->success('');
    }


    //更改密码
    public function changePassword()
    {
        if ($this->request->isPost()) {
            if (!$this->request->post()) {
                $this->error("参数不能为空");
            }
            $params = $this->request->only(['oldPassword', 'newPassword']);

            if (!$this->auth->checkPassword($params['oldPassword'])) {
                $this->error(__('Old password error'));
            }

            $model = $this->auth->getUser();
            $model->startTrans();
            try {
                $model->resetPassword($this->auth->id, $params['newPassword']);
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                $this->error($e->getMessage());
            }

            $this->auth->logout();
            $this->success(('Password has been changed, please login again~'));
        }
    }


    //上传头像
    public function uploadAvatar(): void
    {
        $file = $this->request->file('file');
        $model = $this->auth->getUser();
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload(null, 'other', $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
            $model->resetAvatar($this->auth->id, full_url($attachment['url']));
            $attachment['full_url'] = full_url($attachment['url']);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }
        $this->success(('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    //绑定手机或者邮箱or用户
    public function changeBind()
    {
        if (!$this->request->post()) {
            $this->error("参数不能为空");
        }
        $params  = $this->request->only(['type', 'email', 'mobile', 'username', 'nickname', 'code']);

        $user    = $this->auth->getUser();
        if ($params['type'] == 'email') {
            $user->email = $params['email'];
        } elseif ($params['type'] == 'mobile') {
            $userModel = new User();
            $flag = $userModel->checkCode($user->id, $params['mobile'], $params['code']);

            if ($flag == PublicStatus::PUBLIC_STATUS_ZERO) {
                $this->error("验证码输入不正确");
            }
            if ($flag == PublicStatus::PUBLIC_STATUS_TWO) {
                $this->error("验证码过期,请重新获取");
            }
            $checkMobile = $userModel->checkMobile($params['mobile']);
            if ($checkMobile) {
                $this->error("手机号已经存在");
            }
            $user->mobile = $params['mobile'];
        } elseif ($params['type'] == 'username') {
            $user->username = $params['username'];
        } elseif ($params['type'] == 'nickname') {
            $user->nickname = $params['nickname'];
        }
        $user->save();
        $this->success(('successfully'), [
            'list' => $this->auth->getUserInfo(),
        ]);
    }
}
